# coding: utf-8
__author__ = 'j.tommy'

from flask import Flask, render_template, request, session, redirect, url_for
import hashlib
import logging;
import functools
import json
import os
import sys
from config import app_configs
from modules import User, Blog, Comment, Page, db, create_app
import htmlutil
import jinja_filters

reload(sys)
sys.setdefaultencoding('utf-8')

salt = app_configs['salt']
summary_flag = app_configs['summary_flag']
PAGE_SIZE = app_configs['page_size']

app = create_app()
app.app_context().push()
# set the secret key.  keep this really secret:
app.secret_key = os.urandom(24)
# 用于页面模板进行日期格式化
app.jinja_env.filters['datetimeformat'] = jinja_filters.datetimeformat


def login_require(func):
    """登录拦截器，在需要登录的方法上加上@login_require
    :param func:
    :return:
    """

    @functools.wraps(func)
    def decorator(*args, **kwargs):
        if 'user' in session:
            return func(*args, **kwargs)
        return redirect(url_for('login'))

    return decorator


@app.route('/', methods=['GET'])
@login_require
def index():
    return render_template('index.html', username=session['user'])


def md5(username, password, salt):
    md5 = hashlib.md5()
    md5.update(username + password + salt)
    return md5.hexdigest()


@app.route('/user/register', methods=['GET'])
def to_register():
    return render_template('register.html')


@app.route('/user/register', methods=['POST'])
def register():
    name = request.form['name'].strip()
    username = request.form['username'].strip()
    password1 = request.form['password1'].strip()
    email = request.form['email'].strip()

    result = {}

    md5_password = md5(username, password1, salt)
    try:
        user = User.query.filter_by(username=username).first()
        if user:
            result['msg'] = '用户名已经存在'
            return json.dumps(result)

        user = User.query.filter_by(email=email).first()
        if user:
            result['msg'] = '邮箱已经存在！'
            return json.dumps(result)

        user = User(name=name, username=username, password=md5_password, email=email)
        user.save()
    except Exception, e:
        logging.exception(e)
        result['msg'] = '注册失败！'
    return json.dumps(result)


@app.route('/user/login', methods=['GET'])
def to_login():
    return render_template('login.html')


@app.route('/user/login', methods=['POST'])
def login():
    username = request.form['username'].strip()
    password = request.form['password'].strip()

    result = {'username': username, 'msg': ''}

    if len(username) == 0 or len(password) == 0:
        result['msg'] = u'用户名或密码不能为空'
        return json.dumps(result)

    try:
        user = User.query.filter_by(username=username).first()
    except Exception, e:
        logging.exception(e)
        result['msg'] = u'系统异常，请稍后再试'
        return json.dumps(result)

    if user is None:
        result['msg'] = u'用户不存在'
        return json.dumps(result)

    md5_password = md5(username, password, salt)
    if md5_password == user.password:
        session['user'] = username
        return json.dumps(result)
    result['msg'] = u'用户名或密码错误'
    return json.dumps(result)


@app.route('/logout')
def logout():
    session.pop('user', None)
    return redirect(url_for('index'))


@app.route('/user/change_pwd', methods=['GET'])
def to_change_pwd():
    return render_template('change_pwd.html')


@app.route('/user/change_pwd', methods=['POST'])
def change_pwd():
    username = request.form['username']
    password = request.form['password']
    new_password = request.form['new_password']
    result = {}

    try:
        u = db.session.query(User).filter_by(username=username).first()

        if u:
            md5_pwd = md5(username, password, salt)
            md5_new_password = md5(username, new_password, salt)

            if md5_pwd == u.password:
                db.change_pwd(username, md5_new_password)
            else:
                result['msg'] = u'密码错误'
                return json.dumps(result)
    except db.DBError, e:
        logging.exception(e)
        result['msg'] = u'系统错误，请稍后再试！'
        return json.dumps(result)

    return json.dumps(result)


@app.route('/blog/manage', methods=['GET', 'POST'])
@login_require
def blog_manage():
    page_no = request.args.get('page', type=int, default=1)
    if page_no is None:
        page_no = 1
    username = session['user']
    blog_page = Blog.query.filter_by(username=username).paginate(page_no, PAGE_SIZE)
    print str(blog_page.query)

    page = Page(blog_page)
    return render_template('blog_manage.html', page=page, username=session['user'])


@app.route('/blog/create', methods=['GET'])
@login_require
def to_create_blog():
    blog = Blog(session['user'], '', '')
    return render_template('markdown_editor.html', blog=blog)


@app.route('/blog/create', methods=['POST'])
@login_require
def create_blog():
    res = {'status': 200, 'msg': ''}
    id = request.form['id']
    title = request.form['title'].strip()
    content = request.form['content']
    content = htmlutil.encode(content);
    blog = Blog(session['user'], title, content)
    blog.id = id
    try:
        blog.save()
    except Exception, e:
        res['status'] = 201
        res['msg'] = '保存失败！'
        logging.exception(e)
    return json.dumps(res)


@app.route('/blog/edit/<string:blog_id>')
@login_require
def edit_blog(blog_id):
    blog = db.session.query(Blog).filter_by(id=blog_id).first()
    blog.content = htmlutil.decode(blog.content)
    return render_template('markdown_editor.html', blog=blog)


@app.route('/blog/del/<string:blog_id>', methods=['POST'])
@login_require
def del_blog(blog_id):
    res = {'status': 200, 'msg': ''}
    try:
        blog = db.session.query(Blog).filter_by(id=blog_id).first()
        blog.delete()
    except Exception, e:
        logging.exception(e)
        res['status'] = 201
        res['msg'] = '删除失败'
    return json.dumps(res)


@app.route('/blog/detail/<string:blog_id>')
@login_require
def blog_detail(blog_id):
    blog = db.session.query(Blog).filter_by(id=blog_id).first()
    blog.content = htmlutil.decode(blog.content)
    blog.content = htmlutil.markdown_to_html(blog.content)
    blog.content = htmlutil.decode(blog.content)
    return render_template('blog_detail.html', blog=blog, username=session['user'])


@app.route('/markdown_editor', methods=['GET'])
def to_markdown_editor():
    return render_template('markdown_editor.html')


@app.route('/markdown_2_html', methods=['GET', 'POST'])
def markdown_2_html():
    text = request.form['content']

    if text and len(text) > 0:
        markdown = htmlutil.markdown_to_html(text)
        return markdown
    return None


if __name__ == '__main__':
    app.run(debug=True)